package com.blockmeta.bbs.immodule.fragment;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.adapter.BBSListAdapter;
import com.blockmeta.bbs.businesslibrary.adapter.InforListAdapter;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.net.okhttp.AdapterLoadDataBusiness;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.businesslibrary.net.pojo.InforPOJO;
import com.blockmeta.bbs.businesslibrary.pojo.BBSListZanPOJO;
import com.blockmeta.bbs.businesslibrary.pojo.BBSNewestListPOJO;
import com.blockmeta.bbs.businesslibrary.pojo.PageInfo;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.PersonalHomePageActivity;
import com.blockmeta.bbs.immodule.adapter.personalHomeReplyAdapter;
import com.blockmeta.bbs.immodule.bean.UserAllInfo;
import com.blockmeta.bbs.immodule.bean.UserReply;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

public class PersionalHomePageFragment extends BaseFragment implements OnLoadmoreListener, OnRefreshListener {

    public static final int PAGESIZE = 20;
    @BindView(R2.id.rcv_personal_homepage)
    RecyclerView rcv;
    @BindView(R2.id.list_swipe)
    SmartRefreshLayout list_swipe;
    UserAllInfo userAllInfo;

    public OKHttpGetReq mGetReq;

    private List<InforPOJO.ListBean> authorPostList;
    private List<BBSListZanPOJO.ListBean> userPostList;
    private List<UserReply.Reply> userReplyList;
    private String mLastPost;
    private BaseQuickAdapter mAdapter;
    PageInfo m_pageInfo;


    public static final String CONTENT_TYPE = "type";
    private String mType;

    public static Fragment newInstance(String type) {
        PersionalHomePageFragment f = new PersionalHomePageFragment();
        f.setArguments(buildArgs(type));
        return f;
    }

    public static Bundle buildArgs(final String type) {
        Bundle bundle = new Bundle();
        bundle.putString(CONTENT_TYPE, type);
        return bundle;
    }


    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_personalhomepage, container, false);
    }

    @Override
    public void initView() {
        m_pageInfo = new PageInfo();
        m_pageInfo.setPage(1, PAGESIZE);
        list_swipe.setOnLoadmoreListener(this);
        list_swipe.setOnRefreshListener(this);
        list_swipe.setRefreshFooter(new ClassicsFooter(mContext));
        userAllInfo = ((PersonalHomePageActivity) getActivity()).mUserAllInfo;
        if (userAllInfo == null || userAllInfo.getUserProperty() == null) return;
        rcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mType = (String) getArguments().get(CONTENT_TYPE);
        getContentFromNet(false);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {

        if (m_pageInfo.hasNext()) {
            getContentFromNet(true);
        } else {
            list_swipe.finishLoadmore();
        }

    }

    private void getContentFromNet(final boolean isLoadMore) {
        mGetReq = new OKHttpGetReq(mContext, getUrl());
        mGetReq.getDataWithParam(new Callback() {
            @Override
            public void onError(String resp) {
                ProgressBarUtil.dismissProgress(mContext);
                AdapterLoadDataBusiness.finishLoadAndRefresh(list_swipe);
                mAdapter = new InforListAdapter(null, getActivity());
                AdapterLoadDataBusiness.LoadErrorData(mContext, mAdapter, rcv, new AdapterLoadDataBusiness.ReLoadNet() {
                    @Override
                    public void retryLoadNet() {
                        getContentFromNet(false);
                    }
                });
            }

            @Override
            public void onResponse(String resp, int id) {
                ProgressBarUtil.dismissProgress(mContext);
                AdapterLoadDataBusiness.finishLoadAndRefresh(list_swipe);
                processData(resp, isLoadMore);
            }
        }, initHashMap());

    }



    private void processData(String resp, boolean isLoadMore) {
        m_pageInfo.setPage(m_pageInfo.getPage() + 1, PAGESIZE);
        switch (mType) {
            case PersonalHomePageActivity.CONTENTTYPE_POST:
                try {
                    InforPOJO inforPOJO = GsonUtil.buildGson().fromJson(resp, InforPOJO.class);
                    if (isLoadMore && inforPOJO != null) {
                        if (inforPOJO.getList() == null) {
                            list_swipe.finishLoadmore();
                            return;
                        }
                        mAdapter.addData(inforPOJO.getList());
                    } else if (inforPOJO != null) {
                        mAdapter = new InforListAdapter(inforPOJO.getList(), getActivity());
                        rcv.setAdapter(mAdapter);
                        mAdapter.setNewData(inforPOJO.getList());
                    }
                } catch (Exception e) {
                }
            case PersonalHomePageActivity.CONTENTTYPE_FORUM:
                try {
                    BBSNewestListPOJO bbsNewestListPOJO = GsonUtil.buildGson().fromJson(resp, BBSNewestListPOJO.class);
                    if(bbsNewestListPOJO == null){
                        return;
                    }
                    BBSListZanPOJO inforPOJO = bbsNewestListPOJO.data;
                    if (isLoadMore && inforPOJO != null) {
                        if (inforPOJO.getList() == null) {
                            list_swipe.finishLoadmore();
                            return;
                        }
                        mAdapter.addData(inforPOJO.getList());
                    } else if (inforPOJO != null) {
                        mAdapter = new BBSListAdapter(inforPOJO.getList(), getActivity());
                        rcv.setAdapter(mAdapter);
                        mAdapter.setNewData(inforPOJO.getList());
                    }
                } catch (Exception e) {
                }
                break;
            case PersonalHomePageActivity.CONTENTTYPE_REPLY:
                try {
                    UserReply inforPOJO = GsonUtil.buildGson().fromJson(resp, UserReply.class);
                    if (isLoadMore && inforPOJO != null) {
                        if (inforPOJO.getReplyList() == null) {
                            list_swipe.finishLoadmore();
                            return;
                        }
                        mAdapter.addData(inforPOJO.getReplyList());
                    } else if (inforPOJO != null) {
                        mAdapter = new personalHomeReplyAdapter(R.layout.item_personalhomepage_post, inforPOJO.getReplyList());
                        rcv.setAdapter(mAdapter);
//                        mAdapter.setNewData(inforPOJO.getReplyList());
                    }
                } catch (Exception e) {
                }
                break;
            default:
                break;
        }


    }

    private int getTotalPage(int postCount) {
        return postCount / PAGESIZE + (postCount % PAGESIZE == 0 ? 0 : 1);
    }

    private HashMap<String, String> initHashMap() {
        String type = mType;
        HashMap<String, String> map = new HashMap<>(8);
        switch (type) {
            case PersonalHomePageActivity.CONTENTTYPE_POST:
                map.put("user_name", userAllInfo.getUserProperty().getUsername());
                map.put("page", m_pageInfo.getPage()+ "");
                map.put("num", PAGESIZE + "");
                break;
            case PersonalHomePageActivity.CONTENTTYPE_FORUM:
                map.put("authorid", userAllInfo.getUserProperty().getUid() + "");
                map.put("page", m_pageInfo.getPage()+ "");
                map.put("num", PAGESIZE + "");
                break;
            case PersonalHomePageActivity.CONTENTTYPE_REPLY:
                map.put("authorid", userAllInfo.getUserProperty().getUid() + "");
                map.put("uid", AccountHelper.getUid());
                map.put("page", m_pageInfo.getPage()+ "");
                map.put("num", PAGESIZE + "");
                break;
            default:
                break;
        }
        return map;

    }

    private String getUrl() {
        String type = (String) getArguments().get(CONTENT_TYPE);
        switch (type) {
            case PersonalHomePageActivity.CONTENTTYPE_POST:
                return NetConstant.NEWS_INFO_LIST;
            case PersonalHomePageActivity.CONTENTTYPE_FORUM:
                return NetConstant.BBS_LIST;
            case PersonalHomePageActivity.CONTENTTYPE_REPLY:
                return NetConstant.USER_COMMENTS;
            default:
                break;
        }
        return "";
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.setReboundDuration(500);
        m_pageInfo.setPage(1,PAGESIZE);
        getContentFromNet(false);
    }
}
